//
//  PhotosViewController.m
//  iEPD
//
//  Created by xavi on 12/27/12.
//  Copyright (c) 2012 Mobioneer Ltd. All rights reserved.//
//

#import "VideosViewController.h"
#import "CustomCell.h"
#import "Item.h"
#import "NextVideoViewController.h"
#import "PlayVideoViewController.h"
#import <MobileCoreServices/UTType.h>
#import <MobileCoreServices/UTCoreTypes.h>

#import <MediaPlayer/MediaPlayer.h>
@interface VideosViewController () <UIActionSheetDelegate, UITableViewDataSource, UITableViewDelegate,UIAlertViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    NSMutableArray *_titleArray;
    NSMutableArray *_dateArray;
    NSMutableArray *_fileNameArray;
    NSMutableArray *_sizeArray;
    UIBarButtonItem *_actionBt;
    UIBarButtonItem *_addBt;
    UIActionSheet *_actionSheet;
    NSString *_dateString;
    NSMutableArray *_selectedRowsArray;
    NSMutableArray *_selectedSectionsArray;
    NSInteger _selectedIndexOfActionSheet;
    NSInteger _numSelected;
    BOOL _isCopied;
    NSString *_titleForFolder;
    NSMutableArray *_stringFolderCopied;
    NSMutableArray *_stringFileCopied;
    NSInteger _typeAlert;
    UIImageView *imageView;
}
@end

@implementation VideosViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"TITLE_TAB2", nil);
        self.tabBarItem.image = [UIImage imageNamed:@"ic_tabbar_videos"];
        _actionBt = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(action)];
        _addBt = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPhoto)];
        _titleArray = [[NSMutableArray alloc] init];
        NSArray *titleArray = @[@"Youtube", @"Live"];
        for (int i = 0; i < [titleArray count]; i++) {
            Item *item = [[Item alloc] init];
            item.title = titleArray[i];
            [_titleArray addObject:item];
            item = nil;
        }
        _sizeArray = [[NSMutableArray alloc] init];
        NSArray *sizes = @[@"50Mb", @"30.1Mb", @"12Mb"];
        for (int i = 0; i < [sizes count]; i++) {
            Item *item = [[Item alloc] init];
            // item.size = sizes[i];
            [_sizeArray addObject:item];
            item = nil;
        }
        _fileNameArray = [[NSMutableArray alloc] init];
        NSArray *names = @[@"24h_Hightlight.mp4", @"XFactor.mp4", @"Clip2.mp4"];
        for (int i = 0; i < [names count]; i++) {
            Item *item = [[Item alloc] init];
            item.title = names[i];
            [_fileNameArray addObject:item];
            item = nil;
        }
        _numSelected =0;
        _isCopied = NO;
        _dateArray = [[NSMutableArray alloc] init];
        _stringFolderCopied = [[NSMutableArray alloc] init];
        _stringFileCopied = [[NSMutableArray alloc] init];
        _selectedSectionsArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItems = @[self.editButtonItem,_addBt];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:NSLocalizedString(@"DATE_FORMAT", nil)];
    NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
    _dateString = strDate;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
    if (editing) {
        self.navigationItem.leftBarButtonItem = _actionBt;
        if (_isCopied) {
            _actionBt.enabled = YES;
        } else _actionBt.enabled = NO;
    } else {
        _numSelected = 0;
        self.navigationItem.leftBarButtonItem = nil;
    }
    
}

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)return [_titleArray count];
    else return [_fileNameArray count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"CustomCell";
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];
        cell = [nibs objectAtIndex:0];
        [tableView setEditing:NO animated:NO];
    }
    if(indexPath.section == 0){
        cell.imgView.image = [UIImage imageNamed:@"ic_item_folder"];
        cell.titleLb.text = [[_titleArray objectAtIndex:indexPath.row] title];
        cell.dateLb.text = _dateString;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else {
        cell.imgView.image = [UIImage imageNamed:@"ic_item_video"];
        cell.titleLb.text = [[_fileNameArray objectAtIndex:indexPath.row] title];
        cell.dateLb.text = @"30Mb";
    }
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    _numSelected++;
    _actionBt.enabled = YES;
    Item *item = nil;
    if (indexPath.section == 0) {
        item = _titleArray[indexPath.row];
        
    } else {
        item = _fileNameArray[indexPath.row];
    }
    item.selected = !item.selected;
    if (indexPath.section == 0 && self.editing == NO) {
        NextVideoViewController *nextVideoVC = [[NextVideoViewController alloc] initWithNibName:@"NextVideoViewController" bundle:nil];
        CustomCell *cell =(CustomCell *) [tableView cellForRowAtIndexPath:indexPath];
        nextVideoVC.titleForFolder = cell.titleLb.text;
        [self.navigationController pushViewController:nextVideoVC animated:YES];
        
    }
    if(indexPath.section == 1 && self.editing == NO){
        PlayVideoViewController *playVideo = [[PlayVideoViewController alloc] initWithNibName:@"PlayVideoViewController" bundle:nil];
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:playVideo animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    }
    
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (([[tableView indexPathsForSelectedRows] count] == 0) && (_isCopied == NO)) {
        _actionBt.enabled = NO;
    }
    _numSelected--;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)addPhoto
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"CANCEL", nil)
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:NSLocalizedString(@"ADD_NEW_FOLDER", nil),NSLocalizedString(@"MAKE_A_VIDEO", nil), NSLocalizedString(@"CHOOSE_PHOTO", nil), nil];
    [sheet showInView:[[UIApplication sharedApplication] keyWindow]];
    _selectedIndexOfActionSheet = 0;
    _actionSheet = sheet;
    sheet = nil;
}

- (void) action
{
    
    _selectedIndexOfActionSheet = 1;
    //Order display button of ActionSheet : Delete,Copy,Cut,Rename,Paste,Cancel
    UIActionSheet *sheet;
    switch (_numSelected) {
        case 0:
        {
            if(_isCopied){
                sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                    delegate:self
                                           cancelButtonTitle:NSLocalizedString(@"CANCEL", nil)
                                      destructiveButtonTitle:nil
                                           otherButtonTitles:NSLocalizedString(@"PASTE", nil), nil];
                
            }
        }
            break;
        case 1:
        {
            if (_isCopied){
                sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                    delegate:self
                                           cancelButtonTitle:NSLocalizedString(@"CANCEL", nil)
                                      destructiveButtonTitle:nil
                                           otherButtonTitles:NSLocalizedString(@"DELETE", nil),NSLocalizedString(@"COPY", nil),NSLocalizedString(@"CUT", nil),NSLocalizedString(@"RENAME", nil),NSLocalizedString(@"PASTE", nil),nil];
            } else {
                sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                    delegate:self
                                           cancelButtonTitle:NSLocalizedString(@"CANCEL", nil)
                                      destructiveButtonTitle:nil
                                           otherButtonTitles:NSLocalizedString(@"DELETE", nil),NSLocalizedString(@"COPY", nil),NSLocalizedString(@"CUT", nil),NSLocalizedString(@"RENAME", nil), nil];
            }
        }
            break;
        default:// more than 1
        {
            if (_isCopied) {
                sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                    delegate:self
                                           cancelButtonTitle:NSLocalizedString(@"CANCEL", nil)
                                      destructiveButtonTitle:nil
                                           otherButtonTitles: NSLocalizedString(@"DELETE", nil),NSLocalizedString(@"COPY", nil),NSLocalizedString(@"CUT", nil),NSLocalizedString(@"PASTE", nil), nil];
            } else {
                sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                    delegate:self
                                           cancelButtonTitle:NSLocalizedString(@"CANCEL", nil)
                                      destructiveButtonTitle:nil
                                           otherButtonTitles: NSLocalizedString(@"DELETE", nil),NSLocalizedString(@"COPY", nil),NSLocalizedString(@"CUT", nil), nil];
            }
        }
            break;
    }
    _actionSheet = sheet;
    [sheet showInView:[[UIApplication sharedApplication] keyWindow]];
    NSMutableArray *titleOfButtonArray = nil;
    for (NSInteger i = 0; i < [sheet numberOfButtons]; i++) {
        [titleOfButtonArray addObject:[sheet buttonTitleAtIndex:i]];
        NSLog(@"Title of button :%@",[sheet buttonTitleAtIndex:i]);
    }
    NSLog(@"###################");
}

#pragma mark ActionSheetDelegate
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    NSMutableArray *titleOfButtonArray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < [actionSheet numberOfButtons]; i++) {
        [titleOfButtonArray addObject:[actionSheet buttonTitleAtIndex:i]];
    }
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"CANCEL", nil)]) { //Cancel
        NSLog(@"Pressed button :Cancel");
    }
    
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"ADD_NEW_FOLDER", nil)]) { //Add new folder
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TITLE_APP", nil)
                                                        message:NSLocalizedString(@"MESSAGE_NEW_FOLDER", nil)
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"CANCEL", nil)
                                              otherButtonTitles:NSLocalizedString(@"SAVE", nil), nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        _typeAlert = 1;
        [alert show];
    }
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"MAKE_A_VIDEO", nil)]) { //Take a photo
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSArray *media = [UIImagePickerController
                              availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
            
            if ([media containsObject:(NSString*)kUTTypeImage] == YES) {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                //picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
                [picker setMediaTypes:[NSArray arrayWithObject:(NSString *)kUTTypeImage]];
                
                //picker.delegate = self;
                [self presentModalViewController:picker animated:YES];
                //[picker release];
                
            }
            else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TITLE_APP", nil)
                                                                message:NSLocalizedString(@"CAMERA_NOT_SUPPORT", nil)
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
            }
            
        }
        else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TITLE_APP", nil)
                                                            message:NSLocalizedString(@"NO_CAMERA", nil)
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentModalViewController:picker animated:YES];
        }
    }
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"CHOOSE_PHOTO", nil)]) { //Choose photo
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker animated:YES];
    }
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"DELETE", nil)]) { // Delete
        int i = 0;
        while (i < [_titleArray count]) {
            Item *item = _titleArray[i];
            if (item.selected) {
                [_titleArray removeObject:item];
            } else {
                i++;
            }
        }
        i = 0;
        while (i < [_fileNameArray count]) {
            Item *item = _fileNameArray[i];
            if (item.selected) {
                [_fileNameArray removeObject:item];
            } else {
                i++;
            }
        }
        [self.tableView reloadData];
        NSLog(@"Pressed button : Delete");
    }
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"COPY", nil)]) { // Copy
        _isCopied = YES;
        _actionBt.enabled = YES;
        for (int i = 0; i <[_titleArray count]; i++) {
            Item *item = [[Item alloc] init];
            item = _titleArray[i];
            if(item.selected && ![_stringFolderCopied containsObject:item.title]) [_stringFolderCopied addObject:item.title];
            item = nil;
        }
        for (int i = 0; i <[_fileNameArray count]; i++) {
            Item *item = [[Item alloc] init];
            item = _fileNameArray[i];
            if(item.selected && ![_stringFileCopied containsObject:item.title]) [_stringFileCopied addObject:item.title];
            item = nil;
        }
        NSLog(@"Pressed button :Copy");
        NSLog(@"So copy:%d",[_stringFolderCopied count]);
        NSLog(@"So copy:%d",[_stringFileCopied count]);
    }
    
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"PASTE", nil)]) {
        int i = 0;
        while (i < [_titleArray count]) {
            Item *item = _titleArray[i];
            if (item.shouldDelete) {
                [_titleArray removeObject:item];
            } else {
                i++;
            }
        }
        i = 0;
        while (i < [_fileNameArray count]) {
            Item *item = _fileNameArray[i];
            if (item.shouldDelete) {
                [_fileNameArray removeObject:item];
            } else {
                i++;
            }
        }
        [self.tableView reloadData];
        self.editing = YES;
        i = 0;
        for (i = 0; i < [_stringFolderCopied count]; i++) {
            Item *item = [[Item alloc] init];
            item.title = _stringFolderCopied[i];
            [_titleArray addObject:item];
        }
        i =0;
        for (i = 0; i < [_stringFileCopied count]; i++) {
            Item *item = [[Item alloc] init];
            item.title = _stringFileCopied[i];
            [_fileNameArray addObject:item];
        }
        [self.tableView reloadData];
    }
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"RENAME", nil)]) {
        int temp = 0;
        for (int i = 0 ; i < [_selectedSectionsArray count]; i++) {
            NSIndexPath *index = _selectedSectionsArray[i];
            temp = index.section;
        }
        if (temp == 0) {
            for (int i = 0 ; i < [_titleArray count]; i++) {
                Item *item = [[Item alloc] init];
                item = _titleArray[i];
                if (item.selected) {
                    NSString *string = [NSString stringWithFormat:@"%@ %@ \n%@",NSLocalizedString(@"OLD_NAME", nil),item.title,NSLocalizedString(@"NEW_NAME", nil)];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TITLE_APP", nil) message:string delegate:self cancelButtonTitle:NSLocalizedString(@"CANCEL", nil) otherButtonTitles:NSLocalizedString(@"SAVE", nil), nil];
                    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                    [[alert textFieldAtIndex:0] setPlaceholder:NSLocalizedString(@"HINT", nil)];
                    _typeAlert = 2;
                    [alert show];
                }
            }
        }else if(temp == 1){
            for (int i = 0 ; i < [_fileNameArray count]; i++) {
                Item *item = [[Item alloc] init];
                item = _fileNameArray[i];
                if (item.selected) {
                    NSString *string = [NSString stringWithFormat:@"%@ %@ \n%@",NSLocalizedString(@"OLD_NAME", nil),item.title,NSLocalizedString(@"NEW_NAME", nil)];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TITLE_APP", nil) message:string delegate:self cancelButtonTitle:NSLocalizedString(@"CANCEL", nil) otherButtonTitles:NSLocalizedString(@"SAVE", nil), nil];
                    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                    [[alert textFieldAtIndex:0] setPlaceholder:NSLocalizedString(@"HINT", nil)];
                    _typeAlert = 2;
                    [alert show];
                }
            }
            
        }
    }
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"CUT", nil)]) {
        _isCopied = YES;
        _actionBt.enabled = YES;
        for (int i = 0; i <[_titleArray count]; i++) {
            Item *item = [[Item alloc] init];
            item = _titleArray[i];
            if(item.selected && ![_stringFolderCopied containsObject:item.title]){
                item.shouldDelete = YES;
                [_stringFolderCopied addObject:item.title];
            }
            item = nil;
        }
        for (int i = 0; i <[_fileNameArray count]; i++) {
            Item *item = [[Item alloc] init];
            item = _fileNameArray[i];
            if(item.selected && ![_stringFileCopied containsObject:item.title]){
                item.shouldDelete = YES;
                [_stringFileCopied addObject:item.title];
            }
            item = nil;
        }
    }
}
#pragma  mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	[picker dismissModalViewControllerAnimated:YES];
	imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
}

#pragma mark UIAlertViewDelegate

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (_typeAlert == 1) {
        UITextField *folderName = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1) {
            if([[self trimming:folderName.text] length] > 0){
                Item *item = [[Item alloc] init];
                item.title = folderName.text;
                [_titleArray addObject:item];
                folderName.text = nil;
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TITLE_APP", nil) message:NSLocalizedString(@"REQUIRED_NAME", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"CANCEL", nil) otherButtonTitles:nil, nil];
                alert.alertViewStyle = UIAlertViewStyleDefault;
                _typeAlert = 3;
                [alert show];
            }
        }
    }
    if (_typeAlert == 2) {
        UITextField *fileName = [alertView textFieldAtIndex:0];
        if (buttonIndex == 1){
            if([[self trimming:fileName.text] length] > 0) {
                for (int i = 0; i <[_titleArray count];i++) {
                    Item *item = [[Item alloc] init];
                    item = _titleArray[i];
                    if (item.selected) {
                        item.title = fileName.text;
                    }
                }
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"TITLE_APP", nil) message:NSLocalizedString(@"REQUIRED_NAME", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"CANCEL", nil) otherButtonTitles:nil, nil];
                alert.alertViewStyle = UIAlertViewStyleDefault;
                _typeAlert = 3;
                [alert show];
            }
            fileName.text = nil;
            for (int i = 0; i <[_fileNameArray count]; i++) {
                Item *item = [[Item alloc] init];
                item = _fileNameArray[i];
                if (item.selected) {
                    item.title = fileName.text;
                }
            }
            fileName.text = nil;
        }
    }
    if (_typeAlert == 3) {
        
    }
    [self.tableView reloadData];
}

-(NSString*)trimming:(NSString *)string
{
    return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
